package com.txq.bilibili.app.utils;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;


import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;

import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


import java.io.ByteArrayOutputStream;
import java.io.IOException;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Set;
import java.util.zip.GZIPInputStream;

/**
 * HTTP 网络请求的工具类 包含了GET POST PUT DELETE 这四种请求方法的支持
 */
public class HttpTool {


    //TODO  GET 请求

    /**
     * 执行GET请求
     *
     * @param url 请求的网址
     * @return byte[]-- 网络数据
     */
    public static byte[] get(String url) {

        byte[] ret = null;
        if (url != null) {
            HttpGet request = new HttpGet(url);

            request.setHeader("Accept-Encoding", "gzip");
            ret = requestBase(request);
        }
        return ret;
    }

    public static byte[] requestBase(HttpRequestBase request) {
        byte[] ret = null;
        HttpClient client = new DefaultHttpClient();

        try {
            HttpResponse response = client.execute(request);

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {

                HttpEntity entity = response.getEntity();

                Header header = response.getFirstHeader("Content-Encoding");
                if (header != null) {
                    String value = header.getValue();
                    if ("gzip".equals(value)) {
                        InputStream inputStream = entity.getContent();
                        GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
                        byte[] buf = new byte[128];
                        int len;
                        ByteArrayOutputStream bout = new ByteArrayOutputStream();
                        while (true) {
                            len = gzipInputStream.read(buf);
                            if (len == -1) {
                                break;
                            }
                            bout.write(buf, 0, len);
                        }
                        buf = null;
                        ret = bout.toByteArray();
                        bout.close();
                        gzipInputStream.close();
                        inputStream.close();
                    }
                } else {
                    ret = EntityUtils.toByteArray(entity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    public static byte[] delete(String url) {

        byte[] ret = null;
        if (url != null) {
            HttpDelete request = new HttpDelete(url);
            ret = requestBase(request);
        }
        return ret;
    }

    /**
     * 执行POST 请求
     * POST请求要提交数据 提交数据的方式
     * 本方法提交采用key=value &key=value 的形式
     * 这种数据格式  就是网页中Form表单提交的数据格式
     *
     * @param url    请求的网址
     * @param params Hashmap  包含的参数 也就是key=value的集合
     * @return
     */
    public static byte[] post(String url, HashMap<String, String> params) {
        return post(url, params, "UTF-8");
    }

    public static byte[] post(String url, HashMap<String, String> params, String encoding) {

        byte[] ret = null;
        if (url != null) {
            HttpPost request = new HttpPost(url);
            ret = processEntityRequest(request, params, encoding);
        }
        return ret;
    }

    /**
     * Put请求
     *
     * @param url
     * @param encoding
     * @return
     * @throws java.io.IOException
     * @pd`aram params
     */
    public static byte[] put(String url, HashMap<String, String> params, String encoding) {

        byte[] ret = null;

        if (url != null) {
            HttpPut request = new HttpPut(url);

            ret = processEntityRequest(request, params, encoding);
        }
        return ret;
    }

    /**
     * 本方法实现了Post请求和Put请求 发送key=value
     *
     * @param request
     * @param params
     * @param encoding
     * @return
     */
    private static byte[] processEntityRequest(HttpEntityEnclosingRequestBase request,
                                               HashMap<String, String> params,
                                               String encoding) {

        byte[] ret = null;

        if (request != null) {
            if (params != null) {
                try {

                    LinkedList<NameValuePair> name = new LinkedList<NameValuePair>();

                    Set<String> keyset = params.keySet();
                    for (String key : keyset) {
                        String value = params.get(key);
                        name.add(new BasicNameValuePair(key, value));
                    }
                    if (encoding == null) {
                        encoding = "UTF-8";
                    }
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(name, encoding);
                    request.setEntity(entity);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            HttpClient client = new DefaultHttpClient();
            try {

                HttpResponse response = client.execute(request);
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {

                    HttpEntity entity = response.getEntity();
                    ret = EntityUtils.toByteArray(entity);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return ret;
    }


}
